<template>
  <div id="map" class="map">

  </div>
</template>

<script>
import { listDevelopmentIndexAll } from '@/api/system/city'

window._AMapSecurityConfig = {
  securityJsCode: '652541c3a3d61db3cfc900ffa7d9e124'
}

import AMapLoader from '@amap/amap-jsapi-loader'
import $ from 'jquery'
import { styleData } from '../../utils/pointStyle'
import { mapGetters } from 'vuex'
import { colors } from '../../utils/mapSettings'
import { citys, citys2 } from '../../utils/citys'
import merge from 'webpack-merge'
import { listPark } from '../../api/system/park'
import { calculateCenter } from '../../utils/utils'
export default {
  name: 'Map2',
  props: {
    cityCode: String,
    centerWidth: Number,
    centerHeight: Number,
    isDetail: Boolean,
    showAll: Boolean,
    isCity1: Boolean,
    pointData: Array,
    changeTuglie: Function,
    getDetailInfo: Function
  },
  data() {
    return {
      //当前是否为城市
      isCity: false,
      //地图模块
      map: null,
      //地图显示模块
      district: null,
      polygon: null,
      polygon2: null,
      //绘制地图
      districtExplorer: null,
      cityCode1: null,
      cityName: null,
      //海量点
      massMarks: null,
      //文本标记
      text: 'null',
      //详情---列表数据
      detailsList: [],
      outClick: null,
      //城市名称text列表
      textList: [],
      formateMap:null,
      switch2AreaNode:null,
      //从数据中获取
      cityList:[],
      //第一显示城市列表
      city1List:[],
      //第二显示城市列表
      city2List:[],
      //公司名称
      company_name:"",
      //园区列表
      parksList:[],
      polygon3:[],
      //园区名字列表
      parkTextList:[],
    }
  },
  components: {},

  computed: {
    ...mapGetters(['is_City'])
  },
  created() {
    this.getAllIndex(500000)
    if (this.$route.query.cityName) {
      this.isCity = true
    }
  },
  mounted() {
    this.mapInit()
  },
  methods: {
    //索取所有城市发展指数
    getAllIndex(cityCode){
      listDevelopmentIndexAll(cityCode).then(res => {
        this.cityList = res.rows
        this.city1List = citys
        this.city2List = citys2
        this.city1List.forEach(item => {
          this.cityList.forEach(item1 => {
            if(item.cityCode == item1.cityCode){
              item.developmentIndex = item1.developmentIndex
            }
          })
        })
        this.city2List.forEach(item => {
          this.cityList.forEach(item1 => {
            if(item.cityCode == item1.cityCode){
              item.developmentIndex = item1.developmentIndex
            }
          })
        })
      })
    },
    //清空所有多边形
    clearAllPolygon(){
      this.polygon3.forEach((item,index) =>{
        this.map.remove(item)
      })
    },
    //清空名字
    clearParkText(){
      this.parkTextList.forEach(item => {
        this.map.remove(item)
      })
    },
    //渲染 多边形
    showPolygon(cityCode){
      listPark({cityCode}).then(res => {
        console.log(res,"resres")
        //获取的数据为空
        if(res.rows.length == 0) return
        this.parksList = res.rows.map(item => {
          this.parkTextList.push(new AMap.Text({
            text: item.parkName ,
            anchor: 'center', // 设置文本标记锚点
            topWhenClick:true,
            style: {
              'background-color': 'rgba(0,0,0,0)',
              'border-width': 0,
              'text-align': 'center',
              'font-size': '8px',
              "position":"relative",
              "top":"0",
              "z-index":"999999999",
              'color': '#fff'
            },
            bubble: true,
            position: calculateCenter(JSON.parse(item.parkData))
          }))
          this.parkTextList[this.parkTextList.length - 1].setMap(this.map)
          return {
            id:item.id,
            color:item.parkColor,
            path:JSON.parse(item.parkData)
          }
        })
        //生成产业园区列表
        this.parksList.forEach(item => {
          var temporaryPolygon = new AMap.Polygon({
            path: item.path,
            fillColor: item.color, // 多边形填充颜色
            borderWeight: 0.2, // 线条宽度，默认为 1
            strokeColor: 'red', // 线条颜色
            fillOpacity:0.3,
            extData:{
              id:item.id
            }
          })
          this.polygon3.push(temporaryPolygon)

        })
        this.polygon3.forEach(item=>{
          //给多变形园区 添加点击事件
          item.on('click', (event)=> {
            var id = event.target.getExtData().id
            this.$router.push({
              path: '/model', query: {
                parkId: id
              }
            })
          })
          this.map.add(item);
        })
      })
    },
    addLotPoint() {
      if(this.massMarks){
        this.massMarks.setData(this.pointData)
        this.massMarks.setMap(this.map)
      }
    },
    backHome() {
      this.outClick()
      this.clearAllPolygon()
      this.clearParkText()
    },
    // 初始加载底图
    mapInit: function() {
      var that = this
      AMapLoader.load({
        key: '7060e76c7045c8344955f5e4e649dc01',
        // 插件集合
        plugin: ['AMap.DistrictSearch', 'AMap.ControlBar','AMap.MouseTool'],
        v: '1.4.15',
        // protocol:"",
        AMapUI: {
          version: '1.1',
          plugins: ['overlay/SimpleMarker']
        },
        uiVersion: '2.0' //添加 uiVersion 的脚本版本号
      }).then((AMap) => {
        AMap.plugin(['AMap.DistrictSearch'], () => {
          var opts = {
            subdistrict: 0,
            extensions: 'all',
            level: 'city'
          }
          var district = new AMap.DistrictSearch(opts)
          district.search('重庆市', function(status, result) {
            var bounds = result.districtList[0].boundaries

            var mask = []
            for (var i = 0; i < bounds.length; i += 1) {
              mask.push([bounds[i]])
            }
            that.map = new AMap.Map('map', {
              // mask: mask,
              center: [106.549509, 29.560767],
              disableSocket: true,
              viewMode: '3D',
              showLabel: true,
              labelzIndex: 130,
              pitch: 0,
              zooms:[7.5,20],
              mapStyle: 'amap://styles/dae69c38c5ed2e3cdad1dae8e34f7413'
            })
            that.map.on('zoomchange', function() {
              var zoom = that.map.getZoom() //获取当前地图级别
              if (zoom < 7.8) {
                // that.centerWidth * 7.55 / 751
                // that.map.setZoom(that.centerHeight * 7.55 / 624)
                that.map.setZoom(7.8)
                // that.map.setCenter([107.829509, 30.160967])
                that.map.setCenter([107.830024,30.194134])
              }
            })
            //地图加载完成
            that.map.on("complete", function(){
              //设置背景
              if(!that.isDetail){
                $('.amap-layer').css('background-size','100% auto')
                $(".amap-layer").css("background-repeat", "no-repeat");
                $(".amap-layer").css("background-position", "center");
                $(".amap-layer").css("background-attachment", "fixed");
              }
              that.$emit('loadingSuccess')
            });
            // 海量点开始--------------

            that.setMassMaker()
            that.massMarks.on('click', function(e) {
              console.log(e.data)
              //当前点击点的类型
              const type = e.data.type
              const id = e.data.id
              const marksId = e.data.marksId
              const categoryParentId = e.data.categoryParentId
              //区分首页是否为第一次点击
              console.log(that.isCity, that.isDetail, that.isCity1)
              //在一级页面点击海量点，阻止冒泡
              // if(that.isCity){
              //   e.domEvent.stopPropagation();
              // }
              // if (!that.isCity && !that.isDetail && that.isCity1) {
              //   return
              // }
              //在一级点击海量点
              console.log(that.isDetail,"this.isDetail")
              if (that.isDetail) {
                console.log("挑战model",marksId)
                that.$router.push({
                  path: '/model', query: {
                    marksId:marksId,
                  }
                })
              } else if (that.isCity) {
                that.handleClickRegion(type, categoryParentId)
                //在详情页面的时候点击海量点
                e.domEvent.stopPropagation()
              }
              //高级版 阻止事件冒泡
              e.domEvent.stopPropagation();
            })
            that.massMarks.on('mouseover', function(e) {
              let x_lnglat = e.data.lnglat.Q
              let y_lnglat = e.data.lnglat.R
              let position = [y_lnglat,x_lnglat]
              let company_name = e.data.company_name
              console.log(e.data)
              that.company_name = new AMap.Text({
                text: company_name ,
                anchor: 'center', // 设置文本标记锚点
                topWhenClick:true,
                style: {
                  'background-color': 'rgba(0,0,0,0)',
                  'border-width': 0,
                  'text-align': 'center',
                  'font-size': '12px',
                  "position":"relative",
                  "top":"-10px",
                  "z-index":"999999999",
                  'color': '#fff'
                },
                bubble: true,
                position: position
              })
              console.log(that.company_name,"company_name")
              that.company_name.setMap(null)
              that.company_name.setMap(that.map)
            })
            that.massMarks.on('mouseout', function(e) {
              that.company_name.setMap(null)
            })
            // 海量点结束--------------
            // 初始化地图名称显示
            that.showCityName()
            if (that.isCity || that.isDetail) {
              that.clearCityName()
            }
            that.map.on('zoomchange', function() {
              if (that.isCity) {
                return false
              }
              if (that.map.getZoom() <= 9) {
                that.clearCityName()
                that.showCityName()
              } else {
                that.showCityName2()
              }
            })//缩放变化

            //行政区域操作
            AMapUI.loadUI(['geo/DistrictExplorer'], function(DistrictExplorer) {
              //创建一个实例
              that.districtExplorer = new DistrictExplorer({
                eventSupport: true,
                map: that.map,
                //阻止冒泡
                bubble: false
              })


              /**
               * 初始化绘制地图
               * */
              that.switch2AreaNode = function switch2AreaNode (adcode, callback) {
                if (currentAreaNode && ('' + currentAreaNode.getAdcode() === '' + adcode)) {
                  return
                }
                loadAreaNode(adcode, function(error, areaNode) {
                  if (error) {
                    if (callback) {
                      callback(error)
                    }
                    return
                  }
                  currentAreaNode = window.currentAreaNode = areaNode
                  that.$emit('handleClickRegion', currentAreaNode)
                  //设置当前使用的定位用节点
                  that.districtExplorer.setAreaNodesForLocating([currentAreaNode])
                  refreshAreaNode(areaNode)
                  if (callback) {
                    callback(null, areaNode)
                  }
                })
              }
              that.formateMap = function() {
                var adcode = 500000
                if (that.polygon2) {
                  that.map.remove(that.polygon2)
                }
                that.districtExplorer.loadAreaNode(adcode, function(error, areaNode) {
                  //更新地图视野
                  that.map.setBounds(areaNode.getBounds(), null, null, true)
                  //清除已有的绘制内容
                  that.districtExplorer.clearFeaturePolygons()
                  //绘制子区域

                  that.districtExplorer.renderSubFeatures(areaNode, function(feature, i) {
                    var fillColor = colors[i % colors.length]
                    // var strokeColor = colors[colors.length - 1 - i % colors.length];
                    var strokeColor = colors[i % colors.length]
                    return {
                      cursor: 'default',
                      bubble: true,
                      strokeColor: strokeColor, //线颜色
                      strokeOpacity: 1, //线透明度
                      strokeWeight: 1, //线宽
                      fillColor: fillColor, //填充色
                      fillOpacity: .9 //填充透明度
                    }
                  })

                  //绘制父区域
                  that.districtExplorer.renderParentFeature(areaNode, {
                    cursor: 'default',
                    bubble: true,
                    strokeColor: 'black', //线颜色
                    strokeOpacity: 1, //线透明度
                    strokeWeight: 1, //线宽
                    fillColor: null, //填充色
                    fillOpacity: 0.5 //填充透明度
                  })
                  that.map.setZoom(7.55)
                })
              }
              /**
               * 全部全部地图
               * */
              if (that.cityCode != null) {
                // that.showCityAll()
                that.switch2AreaNode(that.cityCode)
                that.showPolygon(that.cityCode)
                that.$emit('loadingSuccess')
                if(!that.isDetail){
                  that.changeTuglie()
                }
              } else {
                that.switch2AreaNode(500000)
                that.formateMap()
                // that.showCityAll()
              }

              //监听feature的hover事件
              that.districtExplorer.on('featureMouseover', function(e, feature) {
                const name = feature.properties.name
                const position = [feature.properties.center[0], feature.properties.center[1]]
                if (!that.isCity && !that.isDetail) {
                  toggleHoverFeature(feature, e.type === 'featureMouseover',
                    e.originalEvent ? e.originalEvent.lnglat : null)
                  // showCityName(name, position)
                }
              })
              //移出监听feature的事件
              that.districtExplorer.on('featureMouseout', function(e, feature) {
                //移出城市名称
                // that.map.remove(that.text)
                if (!that.isCity && !that.isDetail) {
                  toggleHoverFeature(feature, e.type === 'featureMouseover',
                    e.originalEvent ? e.originalEvent.lnglat : null)
                }
              })
              //监听鼠标在feature上滑动
              that.districtExplorer.on('featureMousemove', function(e, feature) {
                //更新提示位置
                tipMarker.setPosition(e.originalEvent.lnglat)
              })

              // console.log(this.massMarks,"mouseout")

              //feature被点击 内部被点击
              that.districtExplorer.on('featureClick', function(e, feature) {
                if (that.isCity) {
                  that.handleClickRegion()
                } else {
                  var props = feature.properties
                  that.isCity = true
                  that.cityCode1 = props.adcode
                  that.cityName = props.name
                  that.showPolygon(props.adcode)
                  that.$router.push({
                    query:merge(that.$route.query,{'cityCode':props.adcode,'cityName':props.name})
                  })
                  //如果存在子节点
                  // if (props.childrenNum > 0) {
                  //切换聚焦区域
                  //返回区县名称，并去除最后一个字符
                  that.$emit('changeTitle', props.name, props.adcode)
                  that.getDetailInfo(props.adcode)

                  that.switch2AreaNode(props.adcode)
                  that.clearCityName()
                  if(!that.isDetail){
                    that.changeTuglie()
                  }
                }
                // }
              })

              that.outClick = function outClick() {
                that.isCity = false
                that.cityCode1 = null
                that.cityName = null
                that.$emit('changeTitle', '')
                that.switch2AreaNode(500000)

                that.formateMap()

                // that.showCityAll()
              }
              //外部区域被点击
              that.districtExplorer.on('outsideClick', function(e) {
                that.$emit('resetCityInfo')
                that.clearAllPolygon()
                that.clearParkText()
                that.districtExplorer.locatePosition(e.originalEvent.lnglat, function(error, routeFeatures) {
                  if (that.isDetail) {
                    return
                  }
                  if (routeFeatures && routeFeatures.length > 1) {
                    //切换到省级区域
                    that.outClick()
                    if(!that.isDetail){
                      that.changeTuglie()
                    }
                  } else {
                    //切换到全国
                    that.switch2AreaNode(100000)
                  }
                }, {
                  levelLimit: 2
                })
              })

              //当前聚焦的区域
              //当前聚焦的区域
              var currentAreaNode = null
              //鼠标hover提示内容
              var $tipMarkerContent = $('<div class="tipMarker top"></div>')
              var tipMarker = new AMap.Marker({
                content: $tipMarkerContent.get(0),
                offset: new AMap.Pixel(0, 0),
                bubble: true
              })

              //根据Hover状态设置相关样式
              function toggleHoverFeature(feature, isHover, position) {
                tipMarker.setMap(isHover ? that.map : null)
                if (!feature) {
                  return
                }
                var props = feature.properties
                if (isHover) {
                  //更新提示内容
                  $tipMarkerContent.html(' ')
                  //更新位置
                  tipMarker.setPosition(position || props.center)
                }
                $('#area-tree').find('h2[data-adcode="' + props.adcode + '"]').toggleClass('hover', isHover)
                //更新相关多边形的样式
                var polys = that.districtExplorer.findFeaturePolygonsByAdcode(props.adcode)
                for (var i = 0, len = polys.length; i < len; i++) {
                  polys[i].setOptions({
                    fillOpacity: isHover ? 0.6 : 0.9
                  })
                }
              }

              //绘制某个区域的边界
              function renderAreaPolygons(areaNode) {
                //更新地图视野
                that.map.setBounds(areaNode.getBounds(), null, null, true)
                //清除已有的绘制内容
                that.districtExplorer.clearFeaturePolygons()
                let adcode = areaNode._data.geoData.parent.properties.adcode
                if (adcode == '500000') {
                  return
                }
                AMap.plugin(['AMap.DistrictSearch'], () => {
                  // 行政区查询服务
                  var district = new AMap.DistrictSearch({
                    subdistrict: 0,
                    extensions: 'all',
                    level: 'biz_area'
                  })
                  //绘制地图，只显示当前行政区域，自定义边境颜色
                  district.search(adcode.toString(), (status, result) => {
                    // 外多边形坐标数组和内多边形坐标数组
                    var outer = [
                      new AMap.LngLat(-360, 90, true),
                      new AMap.LngLat(-360, -90, true),
                      new AMap.LngLat(360, -90, true),
                      new AMap.LngLat(360, 90, true)
                    ]
                    var holes = result.districtList[0].boundaries
                    var pathArray = [outer]
                    pathArray.push.apply(pathArray, holes)

                    that.polygon2 = new AMap.Polygon({
                      pathL: pathArray,
                      strokeColor: '#0469c1',
                      strokeWeight: 1.5,
                      fillColor: '#123553',
                      fillOpacity: .7,
                      bubble: true
                    })
                    that.polygon2.setPath(pathArray)
                    that.map.add(that.polygon2)
                  })
                })
              }

              //切换区域后刷新显示内容
              function refreshAreaNode(areaNode) {
                that.districtExplorer.setHoverFeature(null)
                renderAreaPolygons(areaNode)
              }
              //加载区域
              function loadAreaNode(adcode, callback) {
                that.districtExplorer.loadAreaNode(adcode, function(error, areaNode) {
                  if (error) {
                    if (callback) {
                      callback(error)
                    }
                    return
                  }
                  // renderAreaPanel(areaNode);
                  if (callback) {
                    callback(null, areaNode)
                  }
                })
              }
            })
          })
        })

      }).catch(e => {
        console.log(e)
      })
    },
    //跳转至详情页面
    handleClickRegion(type, categoryParentId) {
      let cityCode2 = this.$route.query.cityCode
      let cityName2 = this.$route.query.cityName
      if (this.cityCode1) {
        let query = {
          cityCode: this.cityCode1,
          cityName: this.cityName
        }
        if (type) {
          query.type = type
          query.categoryParentId = categoryParentId
        }else{
          query.type = 1
          query.categoryParentId = categoryParentId
        }
        this.$router.push({
          path: '/detail', query
        })
        //通过返回后点入
      } else if (cityCode2) {
        this.cityCode1 = null
        this.cityName = null
        let query = {
          cityCode: cityCode2,
          cityName: cityName2
        }
        if (type) {
          query.type = type
          query.categoryParentId = categoryParentId
        }
        this.$router.push({
          path: '/detail', query
        })
      }
    },
    //设置海量点
    setMassMaker() {
      const size1 = new AMap.Size(10, 10)
      const size2 = new AMap.Size(30, 30)
      const size3 = new AMap.Size(60, 60)
      const styleObjectArr = styleData(size1, size2, size3, new AMap.Pixel(0, 0))
      this.massMarks = new AMap.MassMarks(null, {
        zIndex: 99999999,  // 海量点图层叠加的顺序
        zooms: [3, 18],  // 在指定地图缩放级别范围内展示海量点图层
        alwaysRender: false,
        style: styleObjectArr  // 设置样式对象
      })
      var data = this.pointData
      // this.map.remove(this.massMarks);
      this.massMarks.setData(data)
      this.massMarks.setMap(this.map)
    },
    //动态改变marker
    homeMassMaker(list) {
      const size1 = new AMap.Size(10, 10)
      const size2 = new AMap.Size(30, 30)
      const size3 = new AMap.Size(60, 60)

      const styleObjectArr = styleData(size1, size2, size3, new AMap.Pixel(0, 0))
      this.massMarks = new AMap.MassMarks(null, {
        zIndex: 99999999,  // 海量点图层叠加的顺序
        zooms: [3, 18],  // 在指定地图缩放级别范围内展示海量点图层
        alwaysRender: false,
        style: styleObjectArr  // 设置样式对象
      })
      var data = list


      this.massMarks.setData(data)
      this.massMarks.setMap(this.map)


    },
    //清除所有城市的名称
    clearCityName() {
      this.textList.forEach((item, index) => {
        this.map.remove(this.textList[index])
      })
    },
    //1。不显示被隐藏的城市名称
    showCityName() {
      //只有下面这些城市需要缩放到一定层级才显示城市名称
      this.city1List.forEach((item, index) => {
        this.textList.push(new AMap.Text({
          text: item.name +"</br>"+"<span style='color: #676767;font-size: 12px;position: relative;top: -4px'>"+item.developmentIndex+"</span>",
          anchor: 'center', // 设置文本标记锚点
          topWhenClick:true,
          style: {
            'background-color': 'rgba(0,0,0,0)',
            'border-width': 0,
            'text-align': 'center',
            'font-size': '14px',
            'color': '#000'
          },
          bubble: true,
          position: item.position
        }))
        this.textList[this.textList.length - 1].setMap(null)
        this.textList[this.textList.length - 1].setMap(this.map)
      })
    },
    //2。显示被隐藏的城市名称
    showCityName2() {
      let citys1 = this.city1List.concat(this.city2List)
      console.log(citys1,"citys1")
      citys1.forEach((item, index) => {
        this.textList.push(new AMap.Text({
          text: item.name +"</br>"+"<span style='color: #676767;font-size: 12px;position: relative;top: -4px'>"+item.developmentIndex+"</span>",
          anchor: 'center', // 设置文本标记锚点
          style: {
            'background-color': 'rgba(0,0,0,0)',
            'border-width': 0,
            'text-align': 'center',
            'font-size': '14px',
            'color': '#000'
          },
          bubble: true,
          position: item.position
        }))
        this.textList[this.textList.length - 1].setMap(null)
        this.textList[this.textList.length - 1].setMap(this.map)
      })
    },
    /**
     *绘制 重庆区域
     * */
    showCityAll() {
      const that = this
      //main.js加载的模块 DistrictSearch
      AMap.plugin(['AMap.DistrictSearch'], () => {
        // 行政区查询服务
        that.district = new AMap.DistrictSearch({
          subdistrict: 0,
          extensions: 'all',
          level: 'city'
        })

        /**
         * 只显示当前行政区域
         * */
        if (that.polygon2) {
          that.map.remove(that.polygon2)
        }
        //绘制地图，只显示当前行政区域，自定义边境颜色
        that.district.search('重庆', (status, result) => {
          // 外多边形坐标数组和内多边形坐标数组
          var outer = [
            new AMap.LngLat(-360, 90, true),
            new AMap.LngLat(-360, -90, true),
            new AMap.LngLat(360, -90, true),
            new AMap.LngLat(360, 90, true)
          ]
          var holes = result.districtList[0].boundaries
          var pathArray = [outer]
          pathArray.push.apply(pathArray, holes)
          that.polygon = new AMap.Polygon({
            pathL: pathArray,
            strokeColor: '#030D48',
            strokeWeight: 1.5,
            fillColor: '#030D48',
            fillOpacity: 0.2
          })
          that.polygon.setPath(pathArray)
          that.map.add(that.polygon)

        })
      })
    },
    //清空点标记
    clearMarks(){
      this.map.remove(this.massMarks);
    },

  },
  destroyed() {
    this.map.destroy( );
  }

}
</script>
<style>

</style>
<style lang="scss">


.amap-logo {

  display: none;

  opacity: 0 !important;

}

.amap-copyright {

  opacity: 0;

}


.tipMarker {
  display: flex;
  background: #fff;
}

</style>
